﻿/************************************************************************

 This file is part of EscapeFromPrisonPlanet.

 EscapeFromPrisonPlanet is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 EscapeFromPrisonPlanet is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

************************************************************************/

// All code (c)2012 Scott Bevin. all rights reserved

using Microsoft.Xna.Framework;

namespace LudumDare25Project
{
    internal class Camera
    {
        private Vector2 halfScreenDim = Vector2.Zero;

        public Vector2 TargetPosition = Vector2.Zero;
        public Vector2 Position = Vector2.Zero;

        public float Zoom = 0.55f;
        public float Rotation = 0.0f;

        public Camera(int screenWidth, int screenHeight)
        {
            halfScreenDim = new Vector2((float)(screenWidth), (float)(screenHeight));
            halfScreenDim *= 0.5f;
        }

        public void Update(float dt)
        {
            Vector2 offset = TargetPosition - Position;
            Position += (offset * dt * 10.0f);

#if DEBUG
             DebugDraw.Get.AddText("Camera - Pos: " + Position.ToString() + " Targ: " + TargetPosition.ToString());
#endif
        }

        public Matrix GetWorldMatrix()
        {
            return Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0.0f)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateScale(new Vector3(Zoom, Zoom, 1.0f)) *
                Matrix.CreateTranslation(halfScreenDim.X, halfScreenDim.Y, 0.0f);
        }

        public Vector2 ScreenToWorld(Vector2 pos)
        {
            Matrix mtx = GetWorldMatrix();
            mtx = Matrix.Invert(mtx);
            return Vector2.Transform(pos, mtx);
        }

        public bool ClipTest(Vector2 pos, float radius)
        {
            bool outOfView =
                (pos.X + radius < Position.X - halfScreenDim.X) ||
                (pos.X - radius > Position.X - halfScreenDim.X) ||
                (pos.Y + radius < Position.Y - halfScreenDim.Y) ||
                (pos.Y - radius > Position.Y - halfScreenDim.Y);

            return !outOfView;
        }
    }
}